﻿namespace CRM2011WorkflowUtilities
{
    using System.Activities;
    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Messages;
    using Microsoft.Xrm.Sdk.Query;
    using Microsoft.Xrm.Sdk.Workflow;

    public sealed class BulkSetState : CodeActivity
    {

        [Input("Query for records to Bulk Activate / Deactivate")]
        [RequiredArgument]
        [ReferenceTarget("goalrollupquery")]
        public InArgument<EntityReference> RecordsQuery { get; set; }

        [Input("Target State")]
        [Default("1")]
        [RequiredArgument]
        public InArgument<int> TargetState { get; set; }

        [Input("Target Status")]
        [Default("-1")]
        [RequiredArgument]
        public InArgument<int> TargetStatus { get; set; }


        protected override void Execute(CodeActivityContext activityContext)
        {
            //Create the context and tracing service
            IExecutionContext context = activityContext.GetExtension<IExecutionContext>();
            IOrganizationServiceFactory serviceFactory = activityContext.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            // Initialize the query with the paging information
            QueryExpression query = Helpers.ConvertRollupQueryToQueryExpression(RecordsQuery.Get(activityContext), service);
            query.PageInfo = new PagingInfo();
            query.PageInfo.PageNumber = 1;

            RetrieveMultipleRequest req = new RetrieveMultipleRequest()
            {
                Query = query,
            };

            bool moreRecords = true;
            while (moreRecords)
            {

                RetrieveMultipleResponse resp = (RetrieveMultipleResponse)service.Execute(req);
                foreach (Entity e in resp.EntityCollection.Entities)
                {
                    // Deactivate record
                    SetStateRequest deactivateRequest = new SetStateRequest()
                    {
                        EntityMoniker = new EntityReference(e.LogicalName, e.Id),
                        State = new OptionSetValue(TargetState.Get(activityContext)),
                        Status = new OptionSetValue(TargetStatus.Get(activityContext)),
                    };
                    service.Execute(deactivateRequest);
                }

                // Set the paging information for reading the next page
                moreRecords = resp.EntityCollection.MoreRecords;
                query.PageInfo.PagingCookie = resp.EntityCollection.PagingCookie;
                query.PageInfo.PageNumber++;
            }
        }
    }
}